﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OnlineCellphoneStore.UserPages
{
    public partial class ShopingCart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                UserContext();
                if (Session["Cart"] == null)
                {
                    DataTable cart = new DataTable();
                    cart.Columns.Add("Units Selected", typeof(int));
                    cart.Columns.Add("Available Units", typeof(int));
                    cart.Columns.Add("ID", typeof(int));
                    cart.Columns.Add("Model", typeof(string));
                    cart.Columns.Add("Manufacture", typeof(string));
                    cart.Columns.Add("Year", typeof(string));
                    cart.Columns.Add("Proccessor", typeof(string));
                    cart.Columns.Add("Memory Size", typeof(string));
                    cart.Columns.Add("Price", typeof(double));
                    Session["Cart"] = cart;
                    Session["TotalAmount"] = 0.0;
                }
                if (Request.QueryString["ProductID"] != null)
                {
                    int Id = Int32.Parse(Request.QueryString["ProductID"].ToString());
                    AddRowToCart(Id);
                }
                else
                {
                    ShowCart();
                }
            }
        }
        private void AddRowToCart(int ProductId)
        {
            try
            {
                bool isExist = false;
                DataTable cart = (DataTable)Session["cart"];
                foreach (DataRow row in cart.Rows)
                {
                    if (row[0].ToString() == ProductId.ToString())
                    {
                        isExist = true;
                    }
                }
                if (!isExist)
                {
                    DataRow dr = cart.NewRow();
                    DAL.DBAdapter.CartCellphoneDataTable dt = SQLAdapter.InsertCellphoneToCart(ProductId);
                    dr["ID"] = ProductId;
                    dr["Manufacture"] = dt[0].Manufacture;
                    dr["Model"] = dt[0].Model;
                    dr["Year"] = dt[0].Year;
                    dr["Proccessor"] = dt[0].Proccessor;
                    dr["Memory Size"] = dt[0].MemorySize;
                    dr["Price"] = dt[0].Price;
                    dr["Available Units"] = dt[0].StokAmount;
                    dr["Units Selected"] = 1;
                    cart.Rows.Add(dr);
                    Session["Cart"] = cart;
                    Session["TotalAmount"] = Double.Parse(Session["TotalAmount"].ToString()) + Double.Parse(dt[0].Price.ToString());
                }
                ShowCart();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        protected void CartGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            DataTable cart = (DataTable)Session["cart"];
            double Price = Double.Parse(cart.Rows[e.RowIndex]["Price"].ToString());
            Session["TotalAmount"] = Double.Parse(Session["TotalAmount"].ToString()) - Price;
            cart.Rows[e.RowIndex].Delete();
            Session["Cart"] = cart;
            string Url = "../UserPages/ShopingCart.aspx";
            Response.Redirect(Url, false);
        }
        private void ShowCart()
        {
            DataTable cart = (DataTable)Session["cart"];
            if (cart.Rows.Count == 0)
            {
                TotalAmountHeader.InnerHtml = "No items in the cart yet.";
            }
            else
            {
                TotalAmountHeader.InnerHtml = "Total price: " + Session["TotalAmount"].ToString();
                CartGridView.DataSource = cart;
                CartGridView.DataBind();
            }
        }
        protected void BtnBackToMain_Click(object sender, EventArgs e)
        {
            string Url = "../Main.aspx";
            Response.Redirect(Url, false);
        }
        private void UserContext()
        {
            HandleUserLables();
        }
        private void HandleUserLables()
        {
            // Update labels
            aHelloUser.InnerHtml += Session["UserName"].ToString();
            aLastEntered.InnerHtml += Session["LastVisit"].ToString();
        }
        protected void LogOut_Click(object sender, EventArgs e)
        {
            string Url = "../Main.aspx?LogOut=true";
            Response.Redirect(Url, false);
        }
        protected void CheckOutBtn_Click(object sender, EventArgs e)
        {
            DataTable cart = (DataTable)Session["cart"];
            if (cart.Rows.Count == 0)
            {
                return;
            }
            Response.Redirect("CheckOut.aspx", false);
        }
        private void UpdateTotalPrice()
        {
            DataTable cart = (DataTable)Session["cart"];
            double NewTotalPrice = 0;
            foreach (DataRow row in cart.Rows)
            {
                NewTotalPrice += Double.Parse(row["Units Selected"].ToString()) * Double.Parse(row["Price"].ToString());
            }
            Session["TotalAmount"] = NewTotalPrice;
            ShowCart();
        }
        protected void CartGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            ErrorMessage.Text = "";
            TextBox Value = (TextBox)CartGridView.Rows[e.NewSelectedIndex].Cells[1].FindControl("UnitsWanted");
            int Units;
            bool isNum = Int32.TryParse(Value.Text, out Units);
            if (isNum == true)
            {
                DataTable cart = (DataTable)Session["cart"];
                int Run = 0;
                foreach (DataRow row in cart.Rows)
                {
                    if (Run == e.NewSelectedIndex)
                    {
                        int AvailableUnits = Int32.Parse(row["Available Units"].ToString());
                        if (Units > AvailableUnits)
                        {
                            ErrorMessage.Text = "There is no " + Units + " phones in stock. Maximum amount you can buy is " + AvailableUnits + ".";
                            break;
                        }
                        row["Units Selected"] = Units;
                        break;
                    }
                    else
                    {
                        Run++;
                    }
                }
                CartGridView.DataSource = cart;
                CartGridView.DataBind();
                UpdateTotalPrice();
            }
            else
            {
                ErrorMessage.Text = "Units Wanted must be a number";
            }
        }
    }
}